//
//  AccountViewController.m
//  AntsExpress
//
//  Created by slccper on 16/1/8.
//  Copyright © 2016年 slccper. All rights reserved.
//

#import "AccountViewController.h"
#import "AppDelegate.h"
#import "clsOtherFun.h"
#import <AVFoundation/AVFoundation.h>
#import "DataViewController.h"
#import "AddChangeController.h"
#import "DeliveryPWDController.h"
#import "clsFileFun.h"
#import "LoginPWDViewController.h"
#import "TabbaoController.h"
@interface AccountViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *dataList;
    UIImage *PhotoImage;
}
@property (weak, nonatomic) IBOutlet UIImageView *Picture;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *account;
@property (weak, nonatomic) IBOutlet UILabel *loginId;
@property (weak, nonatomic) IBOutlet UILabel *money;

@end

@implementation AccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(UpMemberPhoto:) name:@"UpLoadImage" object:nil];
    self.title=@"賬戶設置";
    self.Picture.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changePicture:)];
//    NSString *photo = [clsOtherFun getMemberPhoto];
//    NSString *name;
//    NSArray *array = [photo componentsSeparatedByString:@"/"];
//    name = [array lastObject];
    NSString *photostring = [clsOtherFun getMemberPhoto];
     photostring = [photostring stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSData *photodata = [[NSData alloc]initWithBase64EncodedString:photostring options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *image = [UIImage imageWithData:photodata];
    if (image) {
        self.Picture.image =image;
    }else{
        self.Picture.image = [UIImage imageNamed:@"default_profile_pic.png"];
    }
    [self.Picture addGestureRecognizer:tap];
    dataList = [NSMutableArray array];
    [dataList addObjectsFromArray:@[@"個人信息",@"更改收貨密碼",@"更改登入密碼",@"淘寶收貨地址",@""]];//@"更改取貨地址"
//    UIButton *foot = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.tableView.tableFooterView=foot;
    self.account.text = [clsOtherFun getName];
    if ([[clsOtherFun getMemberId] integerValue]!=0) {
        self.loginId.text = [NSString stringWithFormat:@"%ld",(long)[[clsOtherFun getMemberId] integerValue]+600000];
    }
    self.money.text = [NSString stringWithFormat:@"%ld",(long)[[clsOtherFun getVIPMoney]integerValue]];
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    footer.backgroundColor = [UIColor clearColor];
    
    UIButton *logout = [UIButton buttonWithType:UIButtonTypeCustom];
    [logout setTitle:@"登出" forState:UIControlStateNormal];
    [logout setFrame: CGRectMake(-1, 20, ScreenWidth+2, 40)];
    [logout setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [logout addTarget:self action:@selector(Logout:) forControlEvents:UIControlEventTouchUpInside];
    logout.layer.borderColor =[UIColor blackColor].CGColor;
    logout.layer.borderWidth = 1;
    [logout setImage:[UIImage imageNamed:@"logout.jpg"] forState:UIControlStateNormal];
    logout.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [logout setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [footer addSubview:logout];
    self.tableView.tableFooterView = footer;
    ants = [[clsAntsService alloc]init];
    ants.delegate=self;
    // Do any additional setup after loading the view from its nib.
}
-(void)changePicture:(UITapGestureRecognizer *)tap
{
    UIActionSheet *action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相冊" otherButtonTitles:@"相機", nil];
    AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    [action showInView:delegate.window];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)Logout:(id)sender
{
    [clsOtherFun setUser:nil];
    [clsOtherFun setencodeName:@""];
    [self.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginChange" object:nil];
}
#pragma mark - actionSheet delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        UIImagePickerController *ipc=[[UIImagePickerController alloc] init];
        ipc.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        ipc.delegate=self;
        ipc.allowsEditing=NO;
        [self presentViewController:ipc animated:YES completion:nil];
    }else if(buttonIndex==1)
    {
        if (_IOS7) {
            AVAuthorizationStatus authstatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authstatus ==AVAuthorizationStatusRestricted || authstatus ==AVAuthorizationStatusDenied) //用户关闭了权限
            {
                [clsOtherFun ShowMsg:@"沒有權限調用相機"];
                return;
            }
        }
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *ipc= [[UIImagePickerController alloc] init];
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            ipc.showsCameraControls = YES;
            ipc.allowsEditing = NO;
            //  ipc.cameraOverlayView = [self pickerAttachView];
            ipc.delegate = self;
            [self presentViewController:ipc animated:NO completion:nil];
        }else{
            [clsOtherFun ShowMsg:@"沒有權限調用相機"];
        }
        
    }else if(buttonIndex == 2){
        
    }
}
#pragma mark - ImagePickerController
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    NSDictionary *dict=[NSDictionary dictionaryWithObject:image forKey:@"UIImagePickerControllerOriginalImage"];
    [self imagePickerController:picker didFinishPickingMediaWithInfo:dict];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    CGSize size= self.Picture.frame.size;
    size.width=100;
    size.height=100;
    PhotoImage=image;
//    UIImage *image = sender.object;
    NSData *data = UIImageJPEGRepresentation(image, 0.000000001);
    if ([clsOtherFun CheckNetworkStatus:YES]) {
        [clsOtherFun showLoadingView:@"正在上傳數據..."];
        [ants UpLoadMemberPhoto:data];
    }else{
        [clsOtherFun ShowNoNetworkMsg];
    }

//    [[NSNotificationCenter defaultCenter]postNotificationName:@"UpLoadImage" object:image];
    
    image=nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(UIImage*)imageByScalingToSize:(CGSize)destinationSize image:(UIImage*)originalImage
{
    @try {
        UIGraphicsBeginImageContext(destinationSize);
        [originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    @catch (NSException * e) {
        return originalImage;
    }
}
#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"AccountCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if(indexPath.row==dataList.count-1)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
//    cell.imageView.image=[clsOtherFun createImageWithColor:[UIColor blueColor]];
    cell.textLabel.text=[dataList objectAtIndex:indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        DataViewController *data = [[DataViewController alloc]initWithNibName:@"DataViewController" bundle:nil];
        data.isBack=YES;
        [self.navigationController pushViewController:data animated:YES];
    }else if (indexPath.row==1) {
        DeliveryPWDController *delivery = [[DeliveryPWDController alloc]initWithNibName:@"DeliveryPWDController" bundle:nil];
        delivery.isBack=YES;
        [self.navigationController pushViewController:delivery animated:YES];
    }else if (indexPath.row==2) {
        LoginPWDViewController *login = [[LoginPWDViewController alloc]initWithNibName:@"LoginPWDViewController" bundle:nil];
        login.isBack=YES;
        [self.navigationController pushViewController:login animated:YES];
    }else if (indexPath.row == 3){
        TabbaoController *taobao = [[TabbaoController alloc]initWithNibName:@"TabbaoController" bundle:nil];
        taobao.isBack=YES;
        [self.navigationController pushViewController:taobao animated:YES];
    }
//    else if (indexPath.row==1) {
//        AddChangeController *add = [[AddChangeController alloc]initWithNibName:@"AddChangeController" bundle:nil];
//        add.isBack=YES;
//        [self.navigationController pushViewController:add animated:YES];
//    }
}
-(void)UpMemberPhoto:(NSNotification *)sender
{
    UIImage *image = sender.object;
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    if ([clsOtherFun CheckNetworkStatus:YES]) {
        [clsOtherFun showLoadingView:@"正在上傳數據..."];
        [ants UpLoadMemberPhoto:data];
    }else{
        [clsOtherFun ShowNoNetworkMsg];
    }
    
}

-(void)getAntsDataSuccess:(NSInteger)type :(NSMutableDictionary *)pDictionary
{
    [clsOtherFun hideLoadingView];
    NSDictionary *dic = [pDictionary objectForKey:@"data"];
    NSString *status = [dic objectForKey:@"status"];
    if ([status integerValue]==200) {
        self.Picture.image =PhotoImage;
//        NSString *path = [NSString stringWithFormat:@"%@/%@",[clsFileFun getUsersPhotoDir],@"user.png"];
//        [[NSFileManager defaultManager] createDirectoryAtPath:[clsFileFun getUsersPhotoDir] withIntermediateDirectories:YES attributes:nil error:nil];
//        NSString *path =[clsFileFun getFilePath:[clsFileFun getUsersPhotoDir] :@"user.png"];
        
         NSString *str = [clsOtherFun base64forData:UIImageJPEGRepresentation(PhotoImage, 0.001)];
        [clsOtherFun setMemberPhoto:str];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginChange" object:nil];
    }else{
        [clsOtherFun ShowMsg:[dic objectForKey:@"message"]];
    }
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
